import time
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.wait import WebDriverWait
import requests
import logging
logger = logging.getLogger(__name__)
logging.getLogger("selenium").setLevel(logging.DEBUG)


msmbjp_account = [
    {'username': 'truedo','passwd': 'zjx123456'},
]

def getCookies(account_info):
    cookies = []
    loginURL = 'http://www.msmbjp.com/forum/member.php?mod=logging&action=login'
    for elem in account_info:
        account = elem['username']
        password = elem['passwd']
        # try:
        browser = webdriver.Chrome()
        browser.get(loginURL)
        time.sleep(1)
        while "登录" in browser.title:
            list_user = browser.find_element_by_id("login1list")
            list_user.click()
            list_user.click()
            username = browser.find_element_by_name("username")
            username.clear()
            username.send_keys(account)

            psd = browser.find_element_by_name("password")
            psd.clear()
            psd.send_keys(password)
            selected =Select(browser.find_element_by_name("questionid"))
            selected.select_by_index(1)
            commit = browser.find_element_by_name("loginsubmit")
            commit.click()
            WebDriverWait(browser,300).until(lambda x: x.find_element_by_id("userinfo_box"))
            # browser.refresh()

        logger.warning(browser.title)
        cookie =''
        if "互粉之家-免费微信公众号互粉互推互阅增粉吸粉涨粉加粉平台" in browser.title:
            time.sleep(3)
            for elem in browser.get_cookies():
                cookie+=elem["name"]+"="+ elem["value"]+"; "
            if len(cookie) > 0:
                logger.warning("获取cookie成功: %s" % account)
                cookies.append(cookie)
                continue
        else:
            logger.warning("获取cookie失败: %s!" % account)
        # except (Exception,e):
        #     logger.warning(e)
        #     logger.warning("失败 %s!" % account)
        # finally:
        try:
            browser.quit()
        except Exception:
            pass
    return cookies

if __name__=='__main__':
    cookies = getCookies(msmbjp_account)
    logger.warning("cookie获取完成!( Cookie数目为:%d)" % len(cookies))
    headers={
'Accept':'*/*',
'Accept-Encoding':'gzip, deflate, br',
'Accept-Language':'zh-CN,zh;q=0.8',
    'Cookie':cookies[0],
    'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36',
'hd-token':'hello',
'X-Requested-With':'XMLHttpRequest'
}
    req=requests.Session()
    t=req.get(url='http://www.msmbjp.com/?type=read',headers=headers)
    with open('a.html','w') as a:
        a.write(t.text.encode('utf-8').decode('gbk', 'ignore'))
